// pages/stat/stat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: 0,
    type: 0, // 0: 打卡数据, 1: 日志数据
    source: 'account', // 数据来源：'account' 或 'habits'
    clork: false,
    log: false,
    timer: false,
    year: 0,
    month: 0,
    date: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    today: 0,
    Habit_or_Time: false,
    records: [], // 打卡记录数组
    logs: [], // 日志数组
    timers: [], // 计时数组
    userId: '',
    userInfo: null,
    myhabits: [],
    ifHaveLog: false,
    selectedDate: null, // 添加选中日期的状态
    clorkLogs: [], // 打卡统计显示
    habitStats: [], // 习惯统计数据
    imageWidth: 0,
    currentLogType: 0, // 日志类型变量
    dateInfo: '',
    chart: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userId = wx.getStorageSync('userId');
    const userInfo = wx.getStorageSync('userInfo');
    console.log('userId:' + userId);
    console.log('页面参数:', options);

    this.setData({
      userId: userId,
      userInfo: userInfo,
      item: options.item,
      type: options.type || 0,
      source: options.source || 'account',
      habit_id: options.habit_id
    }, () => {
      console.log('item:' + this.data.item);
      console.log('设置后的type值:', this.data.type);
    });

    const app = getApp();
    const globalVar = app.globalData;
    this.setData({
      clork: false,
      allClork: false,
      log: false,
      timer: false,
      logs: globalVar.Logs,
      myhabits: globalVar.My_Habits,
    });

    if (options.item == 1) {
      this.setData({
        allClork: true
      });
      this.getAllRecords();
    }
    if (options.item == 2) {
      this.setData({
        log: true
      });
      this.getLogsByDate();
    }
    if (options.item == 3) {
      this.setData({
        timer: true
      });
      this.getTimers();
    }

    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let todayDate = now.getDate();

    this.dateInit();

    this.setData({
      year: year,
      month: month,
      today: todayDate,
      isToday: '' + year + month + todayDate,
      selectedDate: todayDate
    }, () => {
      if (options.item == 1) {
        this.getAllRecords();
      }
      if (options.item == 2) {
        this.getLogsByDate(year, month, todayDate);
      }
      if (options.item == 3) {
        this.getTimers();
      }
    });
  },

  getTimers: function () {
    const userId = this.data.userId;
    const year = this.data.year;
    const month = this.data.month;
    const day = this.data.today;

    console.log('开始获取计时记录，参数:', {
      userId,
      year,
      month,
      day
    });

    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://127.0.0.1:3001/getTimer',
      method: 'GET',
      data: {
        user_id: userId
      },
      success: (res) => {
        console.log('获取计时记录成功，原始数据:', res.data);

        if (res.data && Array.isArray(res.data)) {
          // 处理数据，格式化计时时长
          const timers = res.data.map(item => {
            console.log('处理计时记录项:', item);

            // 格式化实际用时 (timer_ActualTime 是秒数)
            let actualSeconds = item.timer_ActualTime || 0;
            let keepM = Math.floor(actualSeconds / 60);
            let keepS = actualSeconds % 60;

            // 格式化设定时长 (timer_SetTime 是分钟数)
            let keepTime = item.timer_SetTime || 0;

            // 格式化日期
            let startTime = `${item.timer_Year}-${item.timer_Month}-${item.timer_Day}`;

            // 处理习惯信息
            let habitName = '自定义计时';
            let habitImg = '../../images/default_habit.png';

            if (item.habit_id && item.habit_name) {
              habitName = item.habit_name;
              habitImg = item.habit_img || '../../images/default_habit.png';
            }

            const processedItem = {
              ...item,
              name: habitName,
              habit_img: habitImg,
              timer_year: item.timer_Year,
              timer_month: item.timer_Month,
              timer_day: item.timer_Day,
              startTime: startTime,
              keepTime: keepTime,
              keepM: keepM,
              keepS: keepS
            };

            console.log('处理后的计时记录项:', processedItem);
            return processedItem;
          });

          console.log('所有处理后的计时记录:', timers);

          // 过滤出当前日期的计时记录
          const currentDateTimers = timers.filter(item => {
            const match = parseInt(item.timer_year) === parseInt(year) &&
              parseInt(item.timer_month) === parseInt(month) &&
              parseInt(item.timer_day) === parseInt(day);
            console.log('日期匹配结果:', {
              item: `${item.timer_year}-${item.timer_month}-${item.timer_day}`,
              current: `${year}-${month}-${day}`,
              match: match
            });
            return match;
          });

          console.log('当前日期的计时记录:', currentDateTimers);

          this.setData({
            timers: currentDateTimers
          }, () => {
            console.log('设置 timers 后的数据:', this.data.timers);
          });
        } else {
          console.log('没有计时记录数据或数据格式不正确');
          this.setData({
            timers: []
          });
        }
      },
      fail: (err) => {
        console.error('获取计时记录失败:', err);
        wx.showToast({
          title: '获取计时记录失败',
          icon: 'none'
        });
        this.setData({
          timers: []
        });
      }
    });
  },

  dateInit: function (setYear, setMonth) {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let dateArr = []; //需要遍历的日历数组数据
    let arrLen = 0; //dateArr的数组长度
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + ',' + (month + 1) + ',' + 1).getDay(); //目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
    let obj = {};
    let num = 0;
    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        // 检查该日期是否有记录
        let hasRecord = this.checkDateHasRecord(year, month + 1, num);
        obj = {
          isToday: '' + year + (month + 1) + num,
          dateNum: num,
          weight: 5,
          hasRecord: hasRecord
        };
      } else {
        obj = {};
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    });
    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      });
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      });
    }
  },
  // 添加新方法检查日期是否有记录
  checkDateHasRecord: function (year, month, day) {
    const app = getApp();
    const globalVar = app.globalData;

    // 检查打卡记录 (如果ClorkRecords也在log表里，这段可以移除)
    for (let habit of globalVar.My_Habits) {
      if (habit.ClorkRecords) { // 检查ClorkRecords是否存在
        for (let record of habit.ClorkRecords) {
          if (record.clork_time === '' + year + month + day) {
            return true;
          }
        }
      }
    }

    // 检查日志记录 (现在日志将从后端获取并设置到 this.data.logs)
    // 如果你在getLogsByDate获取数据后立即调用dateInit，这里的logs就是当前日期的数据
    if (this.data.logs) { // 检查logs是否存在
      for (let log of this.data.logs) {
        // 根据你的log表结构，判断日期是否匹配
        if (log.log_year == year && log.log_month == month && log.log_day == day) {
          return true;
        }

      }
    }

    // 检查计时记录 (如果计时记录也在log表里或单独的表中，需要相应的获取和检查逻辑)
    // 目前的代码看起来计时记录records是单独处理的
    if (this.data.records) { // 检查records是否存在
      for (let record of this.data.records) {
        if ('' + record.year + record.month + record.day === '' + year + month + day) {
          return true;
        }
      }
    }

    return false;
  },
  /**
   * 上月切换
   */
  lastMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1)
    });
    this.dateInit(year, month);
  },
  /**
   * 下月切换
   */
  nextMonth: function () {
    //全部时间的月份都是按0~11基准，显示月份才+1
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1)
    });
    this.dateInit(year, month);
  },
  TipToday: function (e) {
    this.setData({
      today: e.currentTarget.dataset.id,
    });
  },
  ifHaveLogs: function (e) {
    const app = getApp();
    var x = app.globalData.Logs;
    for (var i = 0; i < x.length; i++) {
      console.log(x[i].log_CreatedTime);
      if (e.currentTarget.dataset.id == x[i].log_CreatedTime) {
        this.setData({
          ifHaveLog: true
        });
        break;
      }
    }
  },
  // 获取习惯统计数据
  getHabitStats: function () {
    const userId = this.data.userId;
    if (!userId) {
      wx.showToast({
        title: '用户ID未找到',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://127.0.0.1:3001/getHabitStats',
      method: 'GET',
      data: {
        userId: userId
      },
      success: (res) => {
        console.log('获取习惯统计数据成功:', res.data);
        if (res.data && res.data.length > 0) {
          this.setData({
            habitStats: res.data
          });
          // 获取数据后立即创建图表
          this.CreateCanvas();
        } else {
          wx.showToast({
            title: '暂无习惯统计数据',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取习惯统计数据失败', err);
        wx.showToast({
          title: '获取习惯统计数据失败',
          icon: 'none'
        });
      }
    });
  },
  HabitOrTime: function (e) {
    console.log('触发HabitOrTime');
    console.log(e.currentTarget.dataset.id);
    if (e.currentTarget.dataset.id == 1) {
      this.setData({
        Habit_or_Time: false,
      });
    } else if (e.currentTarget.dataset.id == 2) {
      this.setData({
        Habit_or_Time: true,
      });
      // 切换到习惯统计时获取数据
      this.getHabitStats();
    }
  },
  CreateCanvas: function () {
    const habitStats = this.data.habitStats;
    if (!habitStats || habitStats.length === 0) {
      console.log('没有习惯统计数据');
      return;
    }

    var wxCharts = require('wxcharts.js');
    this.setData({
      imageWidth: wx.getSystemInfoSync().windowWidth
    });
    console.log(this.data.imageWidth);
    //计算屏幕宽度比列
    // windowW = this.data.imageWidth/375; // 这行似乎不再需要

    const chartWidth = this.data.imageWidth - 30; // 屏幕宽度减去边距，例如左右各15px
    const chartHeight = 350; // 再次增加高度，为X轴标签留出更多空间

    const categories = habitStats.map(item => item.habit_name);
    const data = habitStats.map(item => item.habit_num);

    new wxCharts({
      canvasId: 'columnCanvas',
      type: 'column',
      animation: true,
      categories: categories,
      series: [{
        name: '打卡次数',
        data: data,
        color: '#8b5c2a'
      }],
      yAxis: {
        // 优化 Y 轴格式，确保显示整数
        format: function (val) {
          return Math.round(val) + '次'; // 四舍五入到最近整数并加上'次'
        },
        title: '打卡次数',
        min: 0,
        max: Math.max(...data) > 0 ? Math.max(...data) + (Math.max(...data) * 0.2) : 5, // 如果最大值大于0，max设置为最大值+20%余量，否则设置为5
        gridColor: '#cccccc',
        fontColor: '#000000',
        fontSize: 12
      },
      xAxis: {
        disableGrid: false,
        type: 'calibration',
        fontColor: '#000000',
        gridColor: '#cccccc',
        fontSize: 11
      },
      extra: {
        column: {
          width: 30
        }
      },
      // 使用动态计算的宽度和增加的高度
      width: chartWidth,
      height: chartHeight, // 之前增加的高度
      dataLabel: true, // 显示数据标签
      dataPointShape: true, // 显示数据点形状
      legend: false,
      background: '#f7f0e6', // 底部背景色改为米色
      padding: 8, // 微调内边距，尝试不同的值
      title: {
        name: '习惯打卡统计',
        color: '#000000',
        fontSize: 14
      }
    });
  },
  lookHuoDong: function (e) {
    const dateNum = e.currentTarget.dataset.datenum;
    const clickedYear = e.currentTarget.dataset.year;
    const clickedMonth = e.currentTarget.dataset.month;

    console.log(`Clicked date: ${clickedYear}-${clickedMonth}-${dateNum}`);

    // 更新下方显示的时间
    this.setData({
      year: clickedYear,
      month: clickedMonth,
      today: dateNum,
      selectedDate: dateNum,
      logs: [],
      timers: [], // 清空计时记录
      records: [] // 清空记录
    });

    // 根据当前页面类型获取相应数据
    if (this.data.timer) {
      this.getTimers(); // 如果是计时页面，重新获取计时记录
    } else {
      this.getLogsByDate(clickedYear, clickedMonth, dateNum); // 其他页面获取日志
    }
  },
  // 获取指定日期的所有打卡记录
  getAllRecords: function () {
    const userId = this.data.userId;
    const year = this.data.year;
    const month = this.data.month;
    const day = this.data.today;

    console.log('getLogs 函数被调用，获取打卡日志');

    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 检查日期参数是否有效 (根据实际需求决定是否需要检查)
    if (!year || !month || !day) {
      console.log('日期参数无效:', {
        year,
        month,
        day
      });
      // 如果日期无效，清空数据并返回
      this.setData({
        clorkLogs: [] // 清空打卡日志数据
      });
      return;
    }

    console.log('请求打卡日志数据，参数:', {
      userId,
      year,
      month,
      day
    });

    wx.request({
      url: 'http://127.0.0.1:3001/getClorkRecords',
      method: 'GET',
      data: {
        userId: userId,
        year: year,
        month: month,
        day: day
      },
      success: (res) => {
        console.log('获取日志成功:', res.data);
        if (res.data && res.data.length > 0) {
          // 在这里处理数据，将习惯名称和图片添加到日志对象中

          this.setData({
            clorkLogs: res.data // 将数据设置到 clorkLogs 变量
          }, () => {
            console.log('设置 clorkLogs 后的数据:', this.data.clorkLogs);
          });
        } else {
          console.log('没有打卡日志数据 (for item=1)');
          this.setData({
            clorkLogs: []
          });
        }
      },
      fail: (err) => {
        console.error('获取日志失败', err);
        wx.showToast({
          title: '获取打卡日志失败',
          icon: 'none'
        });
        this.setData({
          clorkLogs: []
        });
      }
    });
  },
  // 实现根据日期获取日志的函数 (获取打卡日志和日记)
  getLogsByDate: function (year, month, day) {
    const userId = this.data.userId;
    if (!userId) {
      wx.showToast({
        title: '用户ID未找到',
        icon: 'none'
      });
      return;
    }


    // 调用获取打卡日志的接口 (使用实际的 /getAllLogs 接口)
    wx.request({
      url: 'http://127.0.0.1:3001/getAllLogs', // 使用实际的获取打卡日志接口
      method: 'GET',
      data: {
        userId: userId,
        year: year,
        month: month,
        day: day
      },
      success: (res) => {
        console.log('获取打卡日志成功:', res.data);
        if (res.data && Array.isArray(res.data)) {
          // 处理打卡日志数据，并根据当前页面类型设置到不同的变量
          if (this.data.item == 1) { // 如果是打卡记录页面
            this.setData({
              clorkLogs: res.data // 将数据设置到 clorkLogs
            });
            console.log('打卡记录页面，设置 clorkLogs:', this.data.clorkLogs);
          } else if (this.data.item == 2) { // 如果是日志页面
            this.setData({
              records: res.data // 将数据设置到 records
            });
            console.log('日志页面，设置 records (打卡日志):', this.data.records);
          }
        } else {
          if (this.data.item == 1) {
            this.setData({
              clorkLogs: []
            });
          } else if (this.data.item == 2) {
            this.setData({
              records: []
            });
          }
        }
      },
      fail: (err) => {
        console.error('获取打卡日志失败', err);
        this.setData({
          records: []
        });
      }
    });

    // 调用获取日记的接口 (使用 /getDiaryLogsByDate 接口)
    wx.request({
      url: 'http://127.0.0.1:3001/getDiaryLogsByDate', // 获取日记的接口
      method: 'GET',
      data: {
        userId: userId,
        year: year,
        month: month,
        day: day
      },
      success: (res) => {
        console.log('获取日记成功:', res.data);
        if (res.data && Array.isArray(res.data)) {
          // 日记数据直接存入 logs 变量
          this.setData({
            logs: res.data // 将日记数据存入 logs 变量
          });
        } else {
          this.setData({
            logs: []
          });
        }
      },
      fail: (err) => {
        console.error('获取日记失败', err);
        this.setData({
          logs: []
        });
      }
    });

    // 如果还有计时数据需要显示，可以在这里添加类似的 wx.request 调用来获取并更新 timers 变量

  },
  // 新增切换日志类型函数 
  switchLogType: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentLogType: parseInt(type)
    });
  },

});